/*
 * Copyright ©2015-2021 Jaemon. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.gitee.jaemon.spring.adorner.util;

import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.*;

import static freemarker.template.Configuration.VERSION_2_3_30;

/**
 * freemarker工具类
 *
 * @author Jaemon
 * @since 1.0
 */
public final class FreemarkerUtils {

    private FreemarkerUtils() {
    }

    public static void generate(String fileName, String templateName, Object dataModel) {
        generate(fileName, templateName, dataModel, "/adorner/template");
    }

    public static void generate(String fileName, String templateName, Object dataModel, String basePackagePath) {
        Configuration configuration = new Configuration(VERSION_2_3_30);
        configuration.setClassForTemplateLoading(FreemarkerUtils.class, basePackagePath);

        Writer out = null;
        try {
            Template template = configuration.getTemplate(templateName);
            File docFile = new File(fileName);
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile)));
            template.process(dataModel, out);
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}